<template>
  <div class="common-layout">
    <el-container>
      <el-main>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="订单创建日期" prop="dateRange" size="large">
              <el-time-picker
                v-model="dateRange"
                is-range
                range-separator="-"
                start-placeholder="Start time"
                end-placeholder="End time"
                :prefix-icon="Calendar"
                @change="handleDateChange"
              />
            </el-form-item>
          </el-col>

          <el-col :span="6">
            <el-form-item label="供应商名称" prop="supplierId" size="large">
              <el-input v-model="supplierName" size="large" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="供应商编码" prop="erpCode" size="large">
              <el-input v-model="supplierCode" size="large" placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <div style="float: right">
              <el-button type="success" @click="fetchData">查询</el-button>
              <el-button @click="handleReset">重置</el-button>
            </div>
          </el-col>
        </el-row>

        <el-form-item style="margin: 50px 0 20px 0">
          <el-col>
            <el-button @click="handleReset">重置</el-button>
            <div style="float: right">
              <el-button type="success" @click="goToAddPage">新增</el-button>
              <el-button @click="showImportDialog = true">导入</el-button>
            </div>
          </el-col>
        </el-form-item>

        <!-- 弹窗 -->
        <el-dialog title="导入数据" v-model="showImportDialog">
          <el-upload
            class="upload-demo"
            action="http://192.168.100.179:9097/admin/order/import"
            :on-success="handleSuccess"
            :before-upload="beforeUpload"
            ref="uploadRef"
          >
            <el-button @click="importData">选择文件</el-button>
            <div v-if="fileName">上传文件名：{{ fileName }}</div>
            <template #tip>
              <div class="el-upload__tip">仅允许导入xls、xlsx格式文件</div>
            </template>
          </el-upload>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="showImportDialog = false">取消</el-button>
              <el-button type="primary" @click="importData">确认导入</el-button>
            </span>
          </template>
        </el-dialog>
        <el-table :data="orderDatas" style="width: 100%">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="orderCode" label="订单编码" width="180">
            <template #default="{ row }">
              <el-button link type="primary" @click="router.push(`/order/order-detail?id=${row.id}`)">
                {{ row.orderCode }}
              </el-button>
            </template>
          </el-table-column>
          <el-table-column prop="state" label="订单状态" width="180">
            <template #default="{ row }">
              <div v-if="row.state == 1">
                <el-tag size="large" color="#deedd4" :hit="false" style="width: 100px">
                  <el-icon style="vertical-align: middle; color: green; font-size: 30px">
                    <SuccessFilled />
                  </el-icon>
                  <span style="font-size: 14px; vertical-align: middle; color: green">全部确认</span>
                </el-tag>
              </div>
              <div v-else-if="row.state == 2">
                <el-tag size="large" color="#f5e8ff" :hit="false" style="width: 100px">
                  <el-icon style="vertical-align: middle; color: purple; font-size: 30px">
                    <Clock />
                  </el-icon>
                  <span style="font-size: 14px; vertical-align: middle; color: purple">部分确认</span>
                </el-tag>
              </div>
              <div v-else-if="row.state == 3">
                <el-tag size="large" color="#f8d1d1" :hit="false" style="width: 100px">
                  <el-icon style="vertical-align: middle; color: red; font-size: 30px">
                    <CircleCloseFilled />
                  </el-icon>
                  <span style="font-size: 14px; vertical-align: middle; color: red">已拒绝</span>
                </el-tag>
              </div>
              <div v-else-if="row.state == 4">
                <el-tag size="large" color="#fff7e8" :hit="false" style="width: 100px">
                  <el-icon style="vertical-align: middle; color: orange; font-size: 30px">
                    <CircleCheck />
                  </el-icon>
                  <span style="font-size: 14px; vertical-align: middle; color: orange">待确认</span>
                </el-tag>
              </div>
              <div v-else-if="row.state == 5">
                <el-tag size="large" color="#EFEFEF" :hit="false" style="width: 100px">
                  <el-icon style="vertical-align: middle; color: black; font-size: 30px">
                    <CircleCheck />
                  </el-icon>
                  <span style="font-size: 14px; vertical-align: middle; color: black">草稿</span>
                </el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="orderIdentification" label="订单标识" width="180" />
          <el-table-column prop="needConfirm" label="需要确认" width="180">
            <template #default="{ row }">
              <div v-if="Number(row.needConfirm) == 1">
                <el-icon style="vertical-align: middle; font-size: 30px">
                  <svg
                    t="1728888035706"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="4296"
                  >
                    <path d="M512 624a112 112 0 1 0 0-224 112 112 0 0 0 0 224z" p-id="4297" fill="#1afa29" />
                  </svg>
                </el-icon>
                <span style="font-size: 14px; vertical-align: middle">是</span>
              </div>
              <div v-if="Number(row.needConfirm) == 2">
                <el-icon style="vertical-align: middle; font-size: 30px">
                  <svg
                    t="1728888035706"
                    class="icon"
                    viewBox="0 0 1024 1024"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg"
                    p-id="4296"
                  >
                    <path d="M512 624a112 112 0 1 0 0-224 112 112 0 0 0 0 224z" p-id="4297" fill="#8a8a8a" />
                  </svg>
                </el-icon>
                <span style="font-size: 14px; vertical-align: middle">否</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="confirmTime" label="确认时间" width="180" />
          <el-table-column prop="supplierName" label="供应商名称" width="180" />
          <el-table-column prop="supplierCode" label="供应商编码" width="180" />
          <el-table-column prop="createTime" label="订单创建日期" width="180" />
          <el-table-column prop="orderType" label="订单类型" width="180" />
          <el-table-column prop="totalPriceWithTax" label="订单总价（含税）" width="180" />
          <el-table-column prop="totalPriceWithoutTax" label="订单总价（不含税）" width="180" />
          <el-table-column prop="orderCurrency" label="币种" width="180" />
          <el-table-column prop="purchaseOrg" label="采购组织" width="180" />
          <el-table-column prop="purchaseGroup" label="采购组" width="180" />
          <el-table-column prop="companyCode" label="采购企业编码" width="180" />
          <el-table-column prop="companyName" label="采购企业名称" width="180" />
          <el-table-column prop="orderNotes" label="订单备注" width="180" />
          <el-table-column prop="operate" fixed="right" label="操作" width="180">
            <template #default="row">
              <el-button link type="primary" size="small" @click.prevent="deleteRow(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="demo-pagination-block" style="float: right; margin: 20px 0 0 0">
          <el-pagination
            v-model:current-page="Current"
            v-model:page-size="size"
            :page-sizes="[5, 10, 20]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, reactive } from 'vue'
import { Calendar } from '@element-plus/icons-vue'
import { ElButton, ElMessage, ElNotification } from 'element-plus'
import axios from 'axios'
import { useRouter } from 'vue-router'

const dateRange = ref([])
const supplierName = ref('')
const supplierCode = ref('')
const orderDatas = ref([])
// 处理日期变化
const handleDateChange = (value) => {
  dateRange.value = value
}

// 重置表单
const handleReset = () => {
  dateRange.value = []
  supplierName.value = ''
  supplierCode.value = ''
  Current.value = 1
  size.value = 5
  fetchData()
}

const Current = ref(1)
const size = ref(5)
const total = ref(0)
const handleSizeChange = (newSize) => {
  size.value = newSize
  Current.value = 1 // 重置当前页码为1
  fetchData()
}
const handleCurrentChange = (newPage) => {
  Current.value = newPage
  fetchData()
}

// 发送查询请求
const fetchData = async () => {
  try {
    const response = await axios({
      method: 'post',
      url: 'http://192.168.100.179:9097/admin/order/query',
      data: {
        startDate: dateRange.value[0],
        endDate: dateRange.value[1],
        supplierName: supplierName.value,
        supplierCode: supplierCode.value,
        current: Current.value,
        size: size.value
      }
    })
    const result = response.data

    orderDatas.value = result.data.records.map((items) => {
      return {
        id: items.id,
        orderCode: items.orderCode,
        state: items.state,
        orderIdentification: items.orderIdentification,
        needConfirm: items.needConfirm,
        confirmTime: items.confirmTime,
        supplierName: items.supplierName,
        supplierCode: items.supplierCode,
        createTime: items.createTime,
        orderType: items.orderType,
        totalPriceWithTax: items.totalPriceWithTax,
        totalPriceWithoutTax: items.totalPriceWithoutTax,
        orderCurrency: items.orderCurrency,
        purchaseOrg: items.purchaseOrg,
        purchaseGroup: items.purchaseGroup,
        companyCode: items.companyCode,
        companyName: items.companyName,
        publishAsn: items.publishAsn,
        orderNotes: items.orderNotes,
        operate: items.operate
      }
    })

    total.value = result.data.total
  } catch (error) {
    console.error('获取数据失败:', error)
  }
}
onMounted(() => {
  fetchData()
})

//删除接口
const deleteRow = async (id) => {
  console.log(id.row.id)

  try {
    const response = await axios({
      method: 'delete',
      url: 'http://192.168.100.179:9097/admin/order/delete',
      data: {
        id: id.row.id
      }
    })
    if (response.data.code === 0) {
      ElNotification({
        title: 'Success',
        message: '删除成功',
        type: 'success'
      })
      fetchData()
    }
  } catch (error) {
    console.error('删除数据失败:', error)
  }
}

const router = useRouter()
const goToAddPage = () => {
  router.push({ name: 'OrderAdd' })
}

const uploadRef = ref<HTMLInputElement | null>(null)
const beforeUpload = (file: File) => {
  // 获取文件的扩展名
  const extension = file.name.slice(((file.name.lastIndexOf('.') - 1) >>> 0) + 2)

  // 检查文件扩展名是否为 .xls 或 .xlsx
  const isXLS = extension.toLowerCase() === 'xls'
  const isXLSX = extension.toLowerCase() === 'xlsx'

  if (!isXLS && !isXLSX) {
    ElMessage.error('只能上传 xls、xlsx 格式文件!')
    return false
  }
  return true
}
const fileName = ref('')
const handleSuccess = (response: any, file: File, fileList: any) => {
  fileName.value = file.name
  ElMessage.success('文件上传成功')
  showImportDialog.value = false // 关闭对话框
}

const importData = () => {
  // 使用类型断言，明确指定 uploadRef.value 为 HTMLInputElement 类型
  if (uploadRef.value) {
    ;(uploadRef.value as HTMLInputElement).click() // 触发点击上传
  } else {
    ElMessage.error('上传组件未初始化')
  }
}

// 定义响应式变量
const showImportDialog = ref(false)
</script>
<style>
.el-table .el-table__body {
  border-bottom: 1px solid #f2f5f5;
}
.el-table .el-table__header-wrapper tr th {
  background-color: #f2f5f5;
  font-size: 15px;
}
</style>
